<template>
  <div class="scheduling-container">
    <div class="toolbar">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
        @change="updateDateRange"
      />
      <el-select v-model="precision" placeholder="时间精度" @change="updatePrecision">
        <el-option label="小时" value="hour" />
        <el-option label="天" value="day" />
      </el-select>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
      <el-button type="success" @click="addNewTask">添加排程</el-button>
    </div>

    <div class="legend">
      <div class="legend-item">
        <div class="color-block normal"></div>
        <span>正常</span>
      </div>
      <div class="legend-item">
        <div class="color-block outsourced"></div>
        <span>委外</span>
      </div>
      <div class="legend-item">
        <div class="color-block maintenance"></div>
        <span>维修</span>
      </div>
      <div class="legend-item">
        <div class="color-block building"></div>
        <span>自建工单</span>
      </div>
      <div class="legend-item">
        <div class="color-block waiting"></div>
        <span>呆</span>
      </div>
    </div>

    <div class="gantt-wrapper">
      <div class="gantt-header">
        <div class="gantt-header-left">
          <div class="header-cell">工单编号</div>
          <div class="header-cell">工单名称</div>
        </div>
        <div class="gantt-header-right"></div>
      </div>
      <g-gantt-chart
        :chart-start="chartStart"
        :chart-end="chartEnd"
        :precision="precision"
        bar-start="startDate"
        bar-end="endDate"
        date-format="YYYY-MM-DD HH:mm"
        :config="ganttConfig"
      >
        <g-gantt-row 
          v-for="order in productionOrders" 
          :key="order.id" 
          :label="`${order.produceCode} | ${order.produceName}`" 
          :bars="order.tasks" 
        />
      </g-gantt-chart>
    </div>
    
    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="taskDetailVisible"
      title="排程任务详情"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentTask" class="task-detail">
        <div class="detail-item">
          <span class="label">工单编号:</span>
          <span class="value">{{ currentTask.orderCode }}</span>
        </div>
        <div class="detail-item">
          <span class="label">工单名称:</span>
          <span class="value">{{ currentTask.orderName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">开始时间:</span>
          <span class="value">{{ currentTask.startDate }}</span>
        </div>
        <div class="detail-item">
          <span class="label">结束时间:</span>
          <span class="value">{{ currentTask.endDate }}</span>
        </div>
        <div class="detail-item">
          <span class="label">进度:</span>
          <span class="value">{{ currentTask.progress }}%</span>
        </div>
        <div class="detail-item">
          <span class="label">状态:</span>
          <span class="value" :class="'status-' + currentTask.status">
            {{ getStatusText(currentTask.status) }}
          </span>
        </div>
        <div class="detail-item">
          <span class="label">描述:</span>
          <span class="value">{{ currentTask.description || '无' }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="openEditDialog">编辑</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑任务对话框 -->
    <el-dialog
      v-model="taskEditVisible"
      :title="isNewTask ? '添加排程任务' : '编辑排程任务'"
      width="500px"
      destroy-on-close
    >
      <el-form :model="editingTask" label-width="100px" ref="taskForm">
        <el-form-item label="工单" prop="orderId" required v-if="isNewTask">
          <el-select v-model="editingTask.orderId" placeholder="请选择工单" @change="handleOrderChange">
            <el-option 
              v-for="order in availableOrders" 
              :key="order.id" 
              :label="`${order.produceCode} - ${order.produceName}`" 
              :value="order.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" required>
          <el-date-picker
            v-model="taskTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-input v-model="editingTask.progress" disabled suffix-icon="el-icon-percentage">
            <template #append>%</template>
          </el-input>
          <div class="progress-tip">进度根据工单完成数量自动计算</div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editingTask.status" placeholder="请选择状态">
            <el-option label="正常" value="normal" />
            <el-option label="委外" value="outsourced" />
            <el-option label="维修" value="maintenance" />
            <el-option label="自建工单" value="building" />
            <el-option label="呆" value="waiting" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editingTask.description" 
            type="textarea" 
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskEditVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTask">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from "vue";
import moment from "moment";
import { ElMessage } from "element-plus";
import axios from "axios";

// 定义类型
interface Task {
  id: string;
  orderCode: string;
  orderName: string;
  startDate: string;
  endDate: string;
  progress: number;
  status: string;
  description?: string;
  orderId?: string;
  produceNum?: number;     // 计划生产数量
  finishProduceNum?: number; // 已完成数量
  ganttBarConfig: {
    id: string;
    label: string;
    hasHandles: boolean;
    style: {
      background: string;
      borderRadius: string;
      color: string;
    }
  }
}

interface ProductionOrder {
  id: string;
  produceCode: string;
  produceName: string;
  startDate: string;
  entDate: string;
  produceNum: number;
  finishProduceNum: number;
  tasks: Task[];
}

// 对话框相关
const taskDetailVisible = ref(false);
const taskEditVisible = ref(false);
const isNewTask = ref(false);
const currentTask = ref<Task | null>(null);
const editingTask = ref<Task>({
  id: "",
  orderCode: "",
  orderName: "",
  startDate: "",
  endDate: "",
  progress: 0,
  status: "normal",
  description: "",
  orderId: "",
  ganttBarConfig: {
    id: "",
    label: "",
    hasHandles: true,
    style: {
      background: "#10B981",
      borderRadius: "4px",
      color: "white"
    }
  }
});
const taskTimeRange = ref<string[]>([]);

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    normal: "正常",
    outsourced: "委外",
    maintenance: "维修",
    building: "自建工单",
    waiting: "呆"
  };
  return statusMap[status] || status;
};

// 获取状态颜色
const getStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    normal: "#10B981",
    outsourced: "#F59E0B",
    maintenance: "#EF4444",
    building: "#3B82F6",
    waiting: "#6B7280"
  };
  return colorMap[status] || "#10B981";
};

// 甘特图配置
const ganttConfig = ref({
  // 启用拖拽调整
  enableDragDrop: true,
  // 启用调整大小
  enableHandles: true,
  // 点击任务时的回调
  onClick: (barConfig: any) => {
    console.log("点击了任务:", barConfig);
    showTaskDetails(barConfig.id);
  },
  // 任务拖拽完成后的回调
  onDrop: (barConfig: any, newStart: string, newEnd: string) => {
    console.log("任务被拖拽到:", barConfig, newStart, newEnd);
    updateTaskSchedule(barConfig.id, newStart, newEnd);
  }
});

// 日期范围
const today = moment().format("YYYY-MM-DD");
const nextTwoWeeks = moment().add(14, "days").format("YYYY-MM-DD");
const dateRange = ref([today, nextTwoWeeks]);

// 甘特图时间范围
const chartStart = ref(today + " 00:00");
const chartEnd = ref(nextTwoWeeks + " 23:59");

// 时间精度
const precision = ref("day");

// 工单数据
const productionOrders = ref<ProductionOrder[]>([]);
const allOrders = ref<any[]>([]); // 存储所有工单，用于选择

// 可用于添加排程的工单（所有工单，包括已排程的）
const availableOrders = computed(() => {
  // 返回所有工单，无论是否已排程
  return allOrders.value;
});

// 获取工单数据
const fetchProductionOrders = async () => {
  try {
    // 创建一个分页参数，获取所有工单数据
    const params = {
      Index: 1,
      Size: 100 // 假设不会超过100条工单
    };
    
    const response = await axios.get('/api/ProductionModules/GetProducetion', { params });
    
    if (response.data.code === 200) {
      // 存储所有工单数据，用于选择
      allOrders.value = response.data.totalPage;
      
      // 将API返回的工单数据转换为甘特图所需的格式
      const orders: ProductionOrder[] = response.data.totalPage.map((order: any) => ({
        id: order.id,
        produceCode: order.produceCode,
        produceName: order.produceName,
        startDate: order.startDate,
        entDate: order.entDate,
        produceNum: order.produceNum,
        finishProduceNum: order.finishProduceNum,
        tasks: [] // 初始化为空任务列表
      }));
      
      productionOrders.value = orders;
      console.log("获取工单数据成功:", orders);
      
      // 获取工单后，再获取排程数据
      fetchScheduleData();
    } else {
      ElMessage.error("获取工单数据失败");
    }
  } catch (error) {
    console.error("获取工单数据出错:", error);
    ElMessage.error("获取工单数据出错");
  }
};

// 获取排程数据
const fetchScheduleData = async () => {
  try {
    // 这里应该是实际的API调用获取排程数据
    // 由于没有实际的排程API，我们为每个工单创建一些示例任务
    // 在实际应用中，这里应该调用后端API获取真实的排程数据
    
    if (productionOrders.value.length === 0) {
      console.warn("没有工单数据，无法创建排程");
      return;
    }
    
    // 为每个工单创建示例任务
    productionOrders.value = productionOrders.value.map((order) => {
      // 使用工单的开始和结束时间创建任务
      const startDate = order.startDate ? moment(order.startDate).format("YYYY-MM-DD HH:mm") : moment().format("YYYY-MM-DD HH:mm");
      const endDate = order.entDate ? moment(order.entDate).format("YYYY-MM-DD HH:mm") : moment().add(3, "days").format("YYYY-MM-DD HH:mm");
      
      // 计算进度
      let progress = 0;
      if (order.produceNum > 0) {
        progress = Math.floor((order.finishProduceNum / order.produceNum) * 100);
      }
      
      // 创建任务
      const task: Task = {
        id: `task-${order.id}`,
        orderCode: order.produceCode,
        orderName: order.produceName,
        startDate: startDate,
        endDate: endDate,
        progress: progress,
        status: "normal",
        description: `${order.produceName}生产任务`,
        orderId: order.id,
        produceNum: order.produceNum,
        finishProduceNum: order.finishProduceNum,
        ganttBarConfig: {
          id: `task-${order.id}`,
          label: `${order.produceCode} ${progress}%`,
          hasHandles: true,
          style: {
            background: "#10B981",
            borderRadius: "4px",
            color: "white"
          }
        }
      };
      
      return {
        ...order,
        tasks: [task]
      };
    });
    
    console.log("排程数据已更新:", productionOrders.value);
  } catch (error) {
    console.error("获取排程数据失败:", error);
    ElMessage.error("获取排程数据失败");
  }
};

// 更新日期范围
const updateDateRange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    chartStart.value = dateRange.value[0] + " 00:00";
    chartEnd.value = dateRange.value[1] + " 23:59";
  }
};

// 更新时间精度
const updatePrecision = () => {
  // 精度改变后可能需要调整数据格式
  console.log("时间精度已更新为:", precision.value);
};

// 刷新数据
const refreshData = () => {
  fetchProductionOrders(); // 先获取最新的工单数据，然后会自动调用fetchScheduleData
};

// 查找任务
const findTask = (taskId: string): Task | null => {
  for (const order of productionOrders.value) {
    const task = order.tasks.find(t => t.id === taskId);
    if (task) {
      return task;
    }
  }
  return null;
};

// 显示任务详情
const showTaskDetails = (taskId: string) => {
  const task = findTask(taskId);
  if (task) {
    currentTask.value = task;
    taskDetailVisible.value = true;
  }
};

// 打开编辑对话框
const openEditDialog = () => {
  if (!currentTask.value) return;
  
  editingTask.value = JSON.parse(JSON.stringify(currentTask.value));
  taskTimeRange.value = [editingTask.value.startDate, editingTask.value.endDate];
  isNewTask.value = false;
  taskDetailVisible.value = false;
  taskEditVisible.value = true;
};

// 处理工单选择变化
const handleOrderChange = (orderId: string) => {
  const selectedOrder = allOrders.value.find(order => order.id === orderId);
  if (selectedOrder) {
    editingTask.value.orderCode = selectedOrder.produceCode;
    editingTask.value.orderName = selectedOrder.produceName;
    
    // 设置默认开始和结束时间
    const startDate = selectedOrder.startDate ? moment(selectedOrder.startDate).format("YYYY-MM-DD HH:mm") : moment().format("YYYY-MM-DD HH:mm");
    const endDate = selectedOrder.entDate ? moment(selectedOrder.entDate).format("YYYY-MM-DD HH:mm") : moment().add(3, "days").format("YYYY-MM-DD HH:mm");
    taskTimeRange.value = [startDate, endDate];
    
    // 计算进度 - 根据工单的生产数量和已完成数量自动计算
    let progress = 0;
    if (selectedOrder.produceNum > 0) {
      progress = Math.floor((selectedOrder.finishProduceNum / selectedOrder.produceNum) * 100);
    }
    // 将进度设置为只读值
    editingTask.value.progress = progress;
    
    // 保存原始的生产数量和已完成数量，用于后续更新
    editingTask.value.produceNum = selectedOrder.produceNum;
    editingTask.value.finishProduceNum = selectedOrder.finishProduceNum;
  }
};

// 添加新任务
const addNewTask = () => {
  // 即使没有工单，也允许打开对话框，后续可以创建工单
  isNewTask.value = true;
  const now = moment().format("YYYY-MM-DD HH:mm");
  const tomorrow = moment().add(1, "days").format("YYYY-MM-DD HH:mm");
  
  editingTask.value = {
    id: "",
    orderCode: "",
    orderName: "",
    startDate: now,
    endDate: tomorrow,
    progress: 0,
    status: "normal",
    description: "",
    orderId: "",
    produceNum: 0,
    finishProduceNum: 0,
    ganttBarConfig: {
      id: "",
      label: "",
      hasHandles: true,
      style: {
        background: "#10B981",
        borderRadius: "4px",
        color: "white"
      }
    }
  };
  
  taskTimeRange.value = [now, tomorrow];
  taskEditVisible.value = true;
};

// 保存任务
const saveTask = () => {
  // 如果没有选择工单，创建一个新的临时工单
  if (isNewTask.value && !editingTask.value.orderId) {
    // 生成临时ID
    const tempId = 'temp-' + Date.now();
    // 使用用户输入的描述作为工单名称，如果没有则使用默认名称
    const orderName = editingTask.value.description || '新建排程任务';
    
    // 默认设置生产数量为100，已完成数量为0
    const produceNum = 100;
    const finishProduceNum = 0;
    
    // 创建一个临时工单
    const tempOrder = {
      id: tempId,
      produceCode: '临时-' + tempId.substring(0, 8),
      produceName: orderName,
      startDate: editingTask.value.startDate,
      entDate: editingTask.value.endDate,
      produceNum: produceNum,
      finishProduceNum: finishProduceNum,
    };
    
    // 更新进度为0%
    editingTask.value.progress = 0;
    editingTask.value.produceNum = produceNum;
    editingTask.value.finishProduceNum = finishProduceNum;
    
    // 添加到工单列表
    allOrders.value.push(tempOrder);
    
    // 设置当前编辑任务的工单ID
    editingTask.value.orderId = tempId;
    editingTask.value.orderCode = tempOrder.produceCode;
    editingTask.value.orderName = tempOrder.produceName;
  }
  
  if (!taskTimeRange.value || taskTimeRange.value.length !== 2) {
    ElMessage.error("请选择时间范围");
    return;
  }
  
  // 更新时间
  editingTask.value.startDate = taskTimeRange.value[0];
  editingTask.value.endDate = taskTimeRange.value[1];
  
  // 更新甘特图配置
  editingTask.value.ganttBarConfig = {
    id: isNewTask.value ? `task-${editingTask.value.orderId}` : editingTask.value.id,
    label: `${editingTask.value.orderCode} ${editingTask.value.progress}%`,
    hasHandles: true,
    style: {
      background: getStatusColor(editingTask.value.status),
      borderRadius: "4px",
      color: "white"
    }
  };
  
  if (isNewTask.value) {
    // 添加新任务
    const selectedOrder = allOrders.value.find(order => order.id === editingTask.value.orderId);
    if (selectedOrder) {
      // 检查该工单是否已经存在于productionOrders中
      let orderIndex = productionOrders.value.findIndex(order => order.id === editingTask.value.orderId);
      
      if (orderIndex === -1) {
        // 如果不存在，添加新的工单和任务
        const newOrder: ProductionOrder = {
          id: selectedOrder.id,
          produceCode: selectedOrder.produceCode,
          produceName: selectedOrder.produceName,
          startDate: selectedOrder.startDate,
          entDate: selectedOrder.entDate,
          produceNum: selectedOrder.produceNum,
          finishProduceNum: selectedOrder.finishProduceNum,
          tasks: [
            {
              ...editingTask.value,
              id: `task-${selectedOrder.id}`,
              orderCode: selectedOrder.produceCode,
              orderName: selectedOrder.produceName
            }
          ]
        };
        productionOrders.value.push(newOrder);
      } else {
        // 如果存在，添加新任务到现有工单
        productionOrders.value[orderIndex].tasks.push({
          ...editingTask.value,
          id: `task-${selectedOrder.id}-${Date.now()}`, // 确保ID唯一
          orderCode: selectedOrder.produceCode,
          orderName: selectedOrder.produceName
        });
      }
      
      ElMessage.success("添加排程任务成功");
    }
  } else {
    // 更新任务
    for (const order of productionOrders.value) {
      const taskIndex = order.tasks.findIndex(t => t.id === editingTask.value.id);
      if (taskIndex !== -1) {
        // 更新任务
        order.tasks[taskIndex] = JSON.parse(JSON.stringify(editingTask.value));
        ElMessage.success("更新排程任务成功");
        break;
      }
    }
  }
  
  taskEditVisible.value = false;
};

// 更新任务排程
const updateTaskSchedule = (taskId: string, newStart: string, newEnd: string) => {
  for (const order of productionOrders.value) {
    const taskIndex = order.tasks.findIndex(t => t.id === taskId);
    if (taskIndex !== -1) {
      // 更新任务时间
      order.tasks[taskIndex].startDate = newStart;
      order.tasks[taskIndex].endDate = newEnd;
      
      ElMessage.success("更新排程时间成功");
      break;
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchProductionOrders();
});
</script>

<style scoped>
.scheduling-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.progress-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.2;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  align-items: center;
}

.legend {
  display: flex;
  margin-bottom: 20px;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-block {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.normal {
  background-color: #10B981; /* 绿色 */
}

.outsourced {
  background-color: #F59E0B; /* 橙色 */
}

.maintenance {
  background-color: #EF4444; /* 红色 */
}

.building {
  background-color: #3B82F6; /* 蓝色 */
}

.waiting {
  background-color: #6B7280; /* 灰色 */
}

.gantt-wrapper {
  height: calc(100vh - 200px);
  overflow: auto;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.gantt-header {
  display: flex;
  border-bottom: 1px solid #e4e7ed;
}

.gantt-header-left {
  display: flex;
  min-width: 200px;
  border-right: 1px solid #e4e7ed;
}

.header-cell {
  padding: 8px 12px;
  font-weight: bold;
  color: #606266;
  flex: 1;
}

/* 任务详情样式 */
.task-detail {
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.detail-item .label {
  font-weight: bold;
  width: 100px;
  color: #606266;
}

.detail-item .value {
  flex: 1;
}

/* 状态样式 */
.status-normal {
  color: #10B981;
  font-weight: bold;
}

.status-outsourced {
  color: #F59E0B;
  font-weight: bold;
}

.status-maintenance {
  color: #EF4444;
  font-weight: bold;
}

.status-building {
  color: #3B82F6;
  font-weight: bold;
}

.status-waiting {
  color: #6B7280;
  font-weight: bold;
}

/* 自定义甘特图样式 */
:deep(.g-gantt-chart) {
  --gantt-border-color: #e4e7ed;
  --gantt-grid-line-color: #f2f4f7;
  --gantt-bg-grid-primary: #fafafa;
  --gantt-bg-grid-secondary: #ffffff;
  --gantt-bg-bar-handle: #d1d5db;
  --gantt-bg-row-label: #f5f7fa;
  --gantt-font-color: #606266;
}

:deep(.g-gantt-row-label) {
  font-weight: bold;
  padding: 10px;
  min-width: 200px;
}

:deep(.g-gantt-bar) {
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

:deep(.g-gantt-bar:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}
</style>
